package com.ukefu.webim.web.handler.api.rest;

import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.Menu;
import com.ukefu.webim.service.es.WorkOrdersRepository;
import com.ukefu.webim.util.RestResult;
import com.ukefu.webim.util.RestResultType;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.model.WorkOrders;

@RestController
@RequestMapping("/api/workorders/assigned")
@Api(value = "工单服务", description = "未分配工单列表")
public class ApiNotAssignedController extends Handler{

	@Autowired
	private WorkOrdersRepository workOrdersRepository;

	/**
	 * 返回工单列表，支持分页，支持关键词查询，分页参数为 p=1&ps=50，默认分页尺寸为 20条每页
	 * @param request
	 * @param q
	 * @return
	 */
	@RequestMapping( method = RequestMethod.GET)
	@Menu(type = "apps" , subtype = "user" , access = true)
	@ApiOperation("返回我的待办工单列表")
    public ResponseEntity<RestResult> list(HttpServletRequest request , @Valid String q) {
		Page<WorkOrders> workOrdersList = null ;
		BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    	
    	BoolQueryBuilder myBuilder = QueryBuilders.boolQuery();
    	boolQueryBuilder.must(termQuery("assigned" , false)) ;
    	
    	boolQueryBuilder.mustNot(termQuery("status" , UKDataContext.WORKORDERS_CLOSED_STATUS)) ;
    	
    	boolQueryBuilder.must(myBuilder) ;
    	workOrdersList = workOrdersRepository.findByCreater(boolQueryBuilder, false  , false , q, super.getUser(request).getId() ,  new PageRequest(super.getP(request), super.getPs(request), Direction.DESC , "updatetime")) ;
        return new ResponseEntity<>(new RestResult(RestResultType.OK, workOrdersList), HttpStatus.OK);
    }
}